package com.biodiv.community.controller.nacos;

import cn.hutool.http.HttpRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * @author: tianquan
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/nacos")
public class NacosController {

    // https://nacos-io.apifox.cn/api-49133362
    // https://nacos.io/zh-cn/docs/open-api.html

    public static final String DELETE_INSTANCE_URL = "%s/nacos/v1/ns/instance?serviceName=%s&ip=%s&port=%s&namespaceId=%s&group=%s";

    public static final String PUT_INSTANCE_URL = "%s/nacos/v1/ns/instance?serviceName=%s&ip=%s&port=%s&namespaceId=%s&group=%s&weight=%s&enabled=%s";

    public static final String LIST_INSTANCE_URL = "%s/nacos/v1/ns/instance/list?serviceName=%s&namespaceId=%s&group=%s";

    private final NacosConfig nacosConfig;

    @DeleteMapping("/deleteInstance")
    public String deleteInstance(String ip, String port) {
        String serverName = nacosConfig.getServerName();
        String serverAddr = nacosConfig.getServerAddr();
        String namespace = nacosConfig.getNamespace();
        String group = nacosConfig.getGroup();
        String url = String.format(DELETE_INSTANCE_URL, serverAddr, serverName, ip, port, namespace, group);
        // 链式构建请求
        String result = HttpRequest.delete(url)
                .timeout(20000)
                .execute().body();

        return result;
    }

    @PutMapping("/putInstance")
    public String putInstance(String ip, Integer port) {
        String serverName = nacosConfig.getServerName();
        String serverAddr = nacosConfig.getServerAddr();
        String namespace = nacosConfig.getNamespace();
        String group = nacosConfig.getGroup();

        String url = String.format(PUT_INSTANCE_URL, serverAddr, serverName, ip, port, namespace, group, "0", "false");
        // 链式构建请求
        String result = HttpRequest.put(url)
                .timeout(20000)
                .execute().body();

        return result;
    }

    @PutMapping("/listInstance")
    public String listInstance(String serverName) {
        String serverAddr = nacosConfig.getServerAddr();
        String namespace = nacosConfig.getNamespace();
        String group = nacosConfig.getGroup();

        String url = String.format(LIST_INSTANCE_URL, serverAddr, serverName, namespace, group);
        // 链式构建请求
        String result = HttpRequest.get(url)
                .timeout(20000)
                .execute().body();

        return result;
    }

}
